<?php


namespace app\common\model\xiluedu;


use app\common\library\Auth;
use app\common\model\ScoreLog;
use think\Db;
use think\db\Expression;
use think\Exception;
use think\Model;

class SignLog extends Model
{
    protected $name = 'xiluedu_sign_log';

    protected $autoWriteTimestamp = 'int';


    protected $createTime = 'createtime';
    protected $updateTime = false;

    protected $append = [
        'createtime_text'
    ];

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d", $value) : $value;
    }

    /**
     * 积分签到
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function sign(){
        $auth = Auth::instance();
        $sign_log = self::where('user_id',$auth->id)->order('id','desc')->find();
        if(!empty($sign_log)){
            if($sign_log['createtime'] >= strtotime(date('Y-m-d 00:00:00'))
                && $sign_log['createtime']<=strtotime(date('Y-m-d 23:59:59'))){
                throw new Exception("今天已经签到完成");
            }else{
                #今天未签到，判断昨天是否签到
                if($sign_log['createtime']>=strtotime(date('Y-m-d 00:00:00',strtotime('-1 day')))
                    && $sign_log['createtime']<=strtotime(date('Y-m-d 23:59:59',strtotime('-1 day')))){
                    $series_days = $sign_log['series_days']+1;
                    $max_sign = (new SignRule())->order('day','desc')->find();
                    if($max_sign['day']>=$series_days){
                        $where['day'] = $series_days;
                    }else{
                        $where['day'] = $max_sign['day'];
                    }
                }else{
                    //中断
                    $series_days = 1;
                    $where['day'] = $series_days;
                }
            }
        } else{
            //第一次签到
            $series_days = 1;
            $where['day'] = $series_days;
        }
        db()->startTrans();
        try {
            $sign_row = SignRule::where($where)->field('score,vip_score')->find();
            $user_vip = UserVip::where('user_id',$auth->id)->where('expire_time','>=',strtotime(date('Y-m-d')))->find()?:[];
            $score = $user_vip ? $sign_row['vip_score'] : $sign_row['score'];
            $data = [
                'user_id'       =>  $auth->id,
                'score'         =>  $score,
                'series_days'   =>  $series_days,
            ];
            #1.积分签到
            $result = self::create($data);
            $userinfo = \app\common\model\User::getById($auth->id);
            #积分日志
            $result2 =ScoreLog::create([
                'user_id'   =>  $auth->id,
                'score'     =>  $score,
                'before'    =>  $userinfo->score,
                'after'     =>  $userinfo->score+$score,
                'memo'      =>  '打卡签到',
                'createtime'=>  time(),
            ]);
            #用户积分更新
            $userinfo->score = new Expression("score+".$score);
            $result3 = $userinfo->save();
        }catch (Exception $e){
            db()->rollback();
            throw $e;
        }
        db()->commit();
        return $result;
    }

}